package cn.zysoft.his4killsession.controller;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.zysoft.his4killsession.pojo.UserInfo;

@Controller
@RequestMapping("/login")
public class LoginController {

	@RequestMapping("/login.do")
	public String login(HttpServletRequest request,HttpServletResponse response,Model model){
			return "WEB-INF/jsp/login/login";
	}
	@RequestMapping("/tologins.do")
	public String tologin(HttpServletRequest request,Model model){
		try{
			//获取用户 名和密码
			String username = request.getParameter("username");
			String pwd = request.getParameter("pwd");
			model.addAttribute("username",username);
			model.addAttribute("pwd",pwd);
			if(!username.equals(request.getSession().getServletContext().getInitParameter("UserName"))){
				model.addAttribute("error","账号不对！");
				return "WEB-INF/jsp/login/login";
			}else if(!pwd.equals(request.getSession().getServletContext().getInitParameter("PassWord"))){
				model.addAttribute("error","密码不对!");
				return "WEB-INF/jsp/login/login";
			}else if(!username.equals(request.getSession().getServletContext().getInitParameter("UserName")) && !pwd.equals(request.getSession().getServletContext().getInitParameter("PassWord"))){
				model.addAttribute("error","账号密码不对!");
				return "WEB-INF/jsp/login/login";
			}else{
				//登录成功后,以用户对象的形式存入session,获取操作端的IP以及网络信息
				UserInfo users = new UserInfo();
				List<NetworkInterface> wanname = new ArrayList<NetworkInterface>();
				List<InetAddress> ipaddress = new ArrayList<InetAddress>();
				Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();  
		        while (netInterfaces.hasMoreElements()) {  
		            NetworkInterface ni = netInterfaces.nextElement();  
		            wanname.add(ni);
		            Enumeration<InetAddress> ia = ni.getInetAddresses();  
		            while (ia.hasMoreElements()) {  
		                InetAddress ip = ia.nextElement();  
		                ipaddress.add(ip);  
		            }  
		        }
		        users.setUsername(username);
				users.setPassword(pwd);
				users.setWanname(wanname);
				users.setIpaddress(ipaddress);
				HttpSession session = request.getSession();
				session.setAttribute("user",users);
				
				return "WEB-INF/jsp/manager/index"; //return "redirect:/manager/toManager.do";
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
    
}
